package com.hbpu.encap.socket.homework;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Homework03Server {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888)) {
            System.out.println("Waiting for connection...");
            String s = "Briet - Twin.flac";
            try (Socket socket = serverSocket.accept()) {
                System.out.println("Accepted connection from " + socket.getLocalSocketAddress());
                try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
                    s = in.readLine();
                } catch (IOException e) {
                    System.out.println("Error: " + e);
                }
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(("C:\\Users\\马可\\Music\\") + s))) {
                    System.out.println("文件已找到");
                    try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream())) {
                        byte[] buffer = new byte[1024];
                        while (bufferedInputStream.read(buffer) != -1) {
                            bufferedOutputStream.write(buffer);
                        }
                        bufferedOutputStream.flush();
                        System.out.println("文件成功发送！");
                    } catch (IOException e) {
                        System.out.println("文件发送失败！" + e.getMessage());
                    }
                } catch (IOException e) {
                    System.out.println("Error: " + e);
                }
                try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {
                    bufferedWriter.write("已向你发送：" + s + " 音乐文件");
                    bufferedWriter.flush();
                } catch (IOException e) {
                    System.out.println("Error: " + e);
                }
            }
        } catch (IOException e) {
            System.out.println("等待连接时出现错误！" + e.getMessage());
        }
    }
}
